<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>第五天 数据驱动视图</title>
</head>
<body>
	<div id="app">
		<router-link to='/home'>首页</router-link>
		<router-link to='/blog'>我的博客</router-link>
		<router-link to='/login'>登录</router-link>
		<router-link to='/exit'>退出</router-link>
		<router-view/>
	</div>
	<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
	<script type="text/javascript" src="./node_modules/vue-router/dist/vue-router.js"></script>
	<script type="text/javascript">
		Vue.use(VueRouter);
		let Login = {
			data(){
				return{
					name:'',
					pwd:''
				}
			},
			template:`<div>
						<input type="text" v-model='name'>
						<input type="password" v-model='pwd'>
						<input type="button" value='登录' @click='clickHandler'>
					  </div>`,
			methods:{
				clickHandler(){
					//登录
					//把信息存在本地
					localStorage.setItem('user',{name:this.name,pwd:this.pwd});
					sessionStorage.setItem('user',{name:this.name,pwd:this.pwd})
					//编程式导航
					this.$router.push({
						path:'/blog'
					})
				}
			}
		};

		let Home = {
			template:`<div>
						首页
					  </div>`
		};

		let Blog = {
			template:`<div>
						博客
					  </div>`
		};

		let Exit = {
			template:`<div>
						退出
						<input type="button" value='退出' @click='exitClickHandler'>
					  </div>`,
			methods:{
				exitClickHandler(){
					localStorage.clear();
					sessionStorage.clear();
					this.$router.push({
						path:'/login'
					})
				}
			}
		};

		let router = new VueRouter({
			routes:[{
				path:'/',
				redirect:'/home'
			},{
				path:'/login',
				component:Login
			},
			{
				path:'/home',
				component:Home
			},
			{
				path:'/blog',
				component:Blog,
				//给未来的路由做权限控制
				meta:{
					//证明 用户访问该组件的时候需要登录
					auth:true
				}
			},
			{
				path:'/exit',
				component:Exit
			}]
		});

		router.beforeEach((to,from,next)=>{
			console.log(to);
			console.log(from);
			if(to.meta.auth){
				//点击了博客链接  需要登录
				if(localStorage.getItem('user')){
					next();
				}else{
					next({
						path:'/login'
					})
				}
			}else{
				next();//如果不调用会卡住
			}
		})

		new Vue({
			el:'#app',
			router
		})

	</script>
</body>
</html>
